package com.rjwh.dingdong.client.fragment.menu;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.drawbook.DrawBookCatalogMainActivity;
import com.rjwh.dingdong.client.activity.drawbook.DrawBookMyCatalogActivity;
import com.rjwh.dingdong.client.activity.loginregist.ThirdPartyLoginActivity;
import com.rjwh.dingdong.client.activity.mathgame.MathGameActivity;
import com.rjwh.dingdong.client.activity.webbrowser.IntegralMallActivity;
import com.rjwh.dingdong.client.adapter.MainPageModuleListAdapter;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.MainPageModuleData;
import com.rjwh.dingdong.client.bean.localbean.PictureBookMainPageBannerData;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.fragment.BaseFragment;
import com.rjwh.dingdong.client.mvp.presenter.impl.MainPagePresenter;
import com.rjwh.dingdong.client.mvp.view.MainPageView;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.UrlUtil;
import com.rjwh.dingdong.client.util.UtilPublic;
import com.rjwh.dingdong.client.view.DrawBookStepDailog;
import com.rjwh.dingdong.client.view.IndicatorHackyViewPager;
import com.rjwh.dingdong.client.view.NoScrollListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.rjwh.dingdong.client.R.id.main_page_title_txt_left;
import static java.security.AccessController.getContext;

/**
 * 启蒙教育
 *
 * @author 王小珂
 * @ClassName DrawBookFragment
 * @Description TODO(这里用一句话描述这个类的作用)
 * @date 2016-3-28 下午4:13:13
 * @history 1.YYYY-MM-DD author: description:
 */
public class MainPageFragment extends BaseFragment implements MainPageView, ViewPager.OnPageChangeListener, DrawBookStepDailog.OnCancelClickListener {

    @BindView(R.id.loading_layout)
    RelativeLayout loadingLayout;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;

    @BindView(R.id.main_page_top_viewpager)
    IndicatorHackyViewPager mainPageTopViewpager;
    @BindView(R.id.main_page_module_list)
    NoScrollListView mainPageModuleList;
    @BindView(R.id.main_page_mPullRefreshView)
    SwipyRefreshLayout mainPageMPullRefreshView;
    @BindView(R.id.main_page_title_root_rl)
    RelativeLayout mainPageTitleRootRl;
    @BindView(main_page_title_txt_left)
    TextView mainPageTitleTxtLeft;

    private MainPagePresenter presenter;
    List<PictureBookMainPageBannerData> bannerlist = new ArrayList<>();
    List<PictureBookMainPageBannerData> viewList = new ArrayList<>();
    private MainPageModuleListAdapter adapter;
    private DrawBookStepDailog drawBookStepDailog;
    private TimeCount time;
    private MyPagerAdapter viewPagerAdapter;


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.main_page_layout, container, false);
        ButterKnife.bind(this, rootView);
        initView();
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        presenter = new MainPagePresenter(getContext(), this);
        doGetMainPage();
    }

    private void doGetMainPage() {
        hideErrorView();
        showLoadingView();
        presenter.doGetMainPage();
    }

    private void initView() {
        mainPageModuleList.setFocusable(false);
        adapter = new MainPageModuleListAdapter(getContext());
        mainPageModuleList.setAdapter(adapter);
        mainPageMPullRefreshView.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(SwipyRefreshLayoutDirection direction) {
                if (direction == SwipyRefreshLayoutDirection.TOP) {
                    presenter.doGetMainPage();
                }
            }
        });
        viewPagerAdapter = new MyPagerAdapter();
        mainPageTopViewpager.setAdapter(viewPagerAdapter);
        mainPageTopViewpager.addOnPageChangeListener(this);
        mainPageTopViewpager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                    case MotionEvent.ACTION_MOVE:
                        cancelTimer();
                        break;
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL:
                        if (viewPagerAdapter.getCount() > 2) {
                            startTimer();
                        }
                        break;

                    default:
                        break;
                }
                return false;
            }
        });

        if ("1".equals(MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_APP_STARTUP_BADGE))) {
            showMsgTip(true);
        } else {
            showMsgTip(false);
        }
        //当主页弹框满足条件,且url不为空时,执行弹框
        if (MyApplication.spUtil.getBoolPreferenceByParamName(getContext(), LocalConstant.SP_MAINPAGE_DAILOG_SHOW, false) &&
                !AsStrUtils.isEmpty(MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_APP_STARTUP_URL))) {
            showStepDailog(MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_APP_STARTUP_URL));
        }
        if (!AsStrUtils.isEmpty(MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_APP_STARTUP_ACTIONURL))) {
            mainPageTitleTxtLeft.setVisibility(View.VISIBLE);
        } else {
            mainPageTitleTxtLeft.setVisibility(View.GONE);
        }

    }

    private void showMsgTip(boolean isShow) {
        if (isShow) {
            Drawable drawable = getResources().getDrawable(R.drawable.icon_title_msg_new);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//必须设置图片大小，否则不显示
            mainPageTitleTxtLeft.setCompoundDrawables(null, null, drawable, null);
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.icon_title_msg);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//必须设置图片大小，否则不显示
            mainPageTitleTxtLeft.setCompoundDrawables(null, null, drawable, null);
        }
    }

    private void updataBannerView() {
        if (time == null) {
            time = new TimeCount(5 * 1000, 1000);// 构造CountDownTimer对象
        }
//        //无论是否多于1个，都要初始化第一个（index:0）
//        viewList = new ArrayList<>();
//        viewList.add(bannerlist.get(bannerlist.size() - 1));
//        //注意，如果不只1个，mViews比mList多两个（头尾各多一个）
//        //假设：mList为mList[0~N-1], mViews为mViews[0~N+1]
//        // mViews[0]放mList[N-1], mViews[i]放mList[i-1], mViews[N+1]放mList[0]
//        // mViews[1~N]用于循环；首位之前的mViews[0]和末尾之后的mViews[N+1]用于跳转
//        // 首位之前的mViews[0]，跳转到末尾（N）；末位之后的mViews[N+1]，跳转到首位（1）
//        if (bannerlist.size() > 1) { //多于1个要循环
//            for (PictureBookMainPageBannerData bookMainPageBannerData : bannerlist) {
//                viewList.add(bookMainPageBannerData);
//            }
//            //最后一个（index:N+1）
//            viewList.add(bannerlist.get(0));
//        }
        viewPagerAdapter.addList(bannerlist);
        startTimer();
    }

    @Override
    public void onCancel() {
        cancelStepDailog();
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            if (viewPagerAdapter == null) {
                return;
            }
            int count = viewPagerAdapter.getCount();
            if (count > 2) { // 多于2个，才循环
                int index = mainPageTopViewpager.getCurrentItem();
                index = (index + 1) % count;
                mainPageTopViewpager.setCurrentItem(index, true);
                time.start();
            } else {
                time.cancel();
            }
//            if (count > 2) { // 实际上，多于1个，就多于3个
//                int index = mainPageTopViewpager.getCurrentItem();
//                index = index % (count - 2) + 1; //这里修改过
//                mainPageTopViewpager.setCurrentItem(index, true);
//                time.start();
//            }
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        LogUtil.d("onPageSelected", "position:" + position);
//        if (viewList.size() > 1) { //多于1，才会循环跳转
//            if (position < 1) { //首位之前，跳转到末尾（N）
//                position = bannerlist.size(); //注意这里是mList，而不是mViews
//            } else if (position > bannerlist.size()) { //末位之后，跳转到首位（1）
//                position = 1;
//            }
//            mainPageTopViewpager.setCurrentItem(position, true);//false不显示跳转动画
//        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    public class MyPagerAdapter extends PagerAdapter {

        private List<PictureBookMainPageBannerData> bannerlist = new ArrayList<>();

        public void addList(List<PictureBookMainPageBannerData> list) {
            if (list != null) {
                bannerlist.clear();
                bannerlist.addAll(list);
                notifyDataSetChanged();
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            ImageView imageView = new ImageView(getContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            if (bannerlist.get(position).getBannerurl() != null) {
                Glide.with(getContext()).load(bannerlist.get(position).getBannerurl()).placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_pic_holder).dontAnimate().into(imageView);
            }
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (bannerlist.get(position).getBookid() != null) {
                        //banner图跳转
                        String actionurl = bannerlist.get(position).getActionurl();
                        if (actionurl != null) {
                            UrlUtil.handelUrl(getContext(), actionurl, true);
                        }

                    }
                }
            });
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getCount() {
            return bannerlist == null ? 0 : bannerlist.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
    }

    @OnClick({R.id.main_page_title_txt_right, R.id.btn_refresh, main_page_title_txt_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_page_title_txt_right:
                // 绘本馆选择框
                showCatalogPopWD();
                break;

            case main_page_title_txt_left:
                //to消息列表
                showMsgTip(false);
                //TODO
                UrlUtil.handelUrl(getContext(), MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_APP_STARTUP_ACTIONURL), true);
                break;

            case R.id.btn_refresh:
                doGetMainPage();
                break;

        }
    }

    /**
     * 绘本馆选折框
     */
    private void showCatalogPopWD() {
        View mPopWindowView = getActivity().getLayoutInflater().inflate(R.layout.drawbook_popupwindow, null);
        // Focusable 为True，PopupWindow的点击事件才会相应
        final PopupWindow mPopWindow = new PopupWindow(mPopWindowView, UtilPublic.dp2px(140, getContext()), ViewGroup.LayoutParams.WRAP_CONTENT, true);
        // 必须在代码中设置一下背景色，点击外面不会隐藏此弹窗
        mPopWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        // Focusable 为False时，不执行则点击外面不会隐藏此弹窗
        mPopWindow.setOutsideTouchable(true);
        //设置动画效果
        mPopWindow.setAnimationStyle(R.style.popmenu_anim_style);
        // 显示在View的正下方,设置偏移量来调整位置
        mPopWindow.showAsDropDown(mainPageTitleRootRl, mainPageTitleRootRl.getWidth() - mPopWindow.getWidth() - UtilPublic.dp2px(8, getContext()), 0);
        TextView catalogBtn = (TextView) mPopWindowView.findViewById(R.id.drawbook_pop_catalog);
        TextView mathGameBtn = (TextView) mPopWindowView.findViewById(R.id.drawbook_pop_mathgame);
        TextView myCatalogBtn = (TextView) mPopWindowView.findViewById(R.id.drawbook_pop_my_catalog);
        TextView intergalMallBtn = (TextView) mPopWindowView.findViewById(R.id.drawbook_pop_intergal_mall);
        catalogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 绘本馆
                Intent intent = new Intent(getActivity(), DrawBookCatalogMainActivity.class);
                startActivity(intent);
                mPopWindow.dismiss();
            }
        });
        mathGameBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //游戏主页
                MathGameActivity.startActivity(getContext());
                mPopWindow.dismiss();
            }
        });
        myCatalogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MyApplication.spUtil.getBoolPreferenceByParamName(getContext(),
                        LocalConstant.SP_IS_LOGINED)) {
                    // 我的绘本
                    Intent myCatalog = new Intent(getContext(), DrawBookMyCatalogActivity.class);
                    startActivity(myCatalog);
                    mPopWindow.dismiss();
                } else {
                    mPopWindow.dismiss();
                    ThirdPartyLoginActivity.startActivity(getContext());
                }
            }
        });
        intergalMallBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MyApplication.spUtil.getBoolPreferenceByParamName(getContext(),
                        LocalConstant.SP_IS_LOGINED)) {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), IntegralMallActivity.class);
                    intent.putExtra("navColor", "#ffffff");    //配置导航条的背景颜色，请用#ffffff长格式。
                    intent.putExtra("titleColor", "#333333");    //配置导航条标题的颜色，请用#ffffff长格式。
                    intent.putExtra("url", "http://emall.whtdlx.com/" + MyApplication.spUtil.getStrPreferenceByParamName(getContext(), LocalConstant.SP_USERID));    //配置自动登陆地址，每次需服务端动态生成。
                    startActivity(intent);

                    IntegralMallActivity.creditsListener = new IntegralMallActivity.CreditsListener() {
                        /**
                         * 当点击分享按钮被点击
                         * @param shareUrl 分享的地址
                         * @param shareThumbnail 分享的缩略图
                         * @param shareTitle 分享的标题
                         * @param shareSubtitle 分享的副标题
                         */
                        public void onShareClick(WebView webView, String shareUrl, String shareThumbnail, String shareTitle, String shareSubtitle) {
                            //当分享按钮被点击时，会调用此处代码。在这里处理分享的业务逻辑。
                            new AlertDialog.Builder(webView.getContext())
                                    .setTitle("分享信息")
                                    .setItems(new String[]{"标题：" + shareTitle, "副标题：" + shareSubtitle, "缩略图地址：" + shareThumbnail, "链接：" + shareUrl}, null)
                                    .setNegativeButton("确定", null)
                                    .show();
                        }

                        /**
                         * 当点击“请先登录”按钮唤起登录时，会调用此处代码。
                         * 用户登录后，需要将CreditsActivity.IS_WAKEUP_LOGIN变量设置为true。
                         * @param webView 用于登录成功后返回到当前的webview刷新登录状态。
                         * @param currentUrl 当前页面的url
                         */
                        public void onLoginClick(WebView webView, String currentUrl) {
                            //当未登录的用户点击去登录时，会调用此处代码。
                            //用户登录后，需要将CreditsActivity.IS_WAKEUP_LOGIN变量设置为true。
                            //为了用户登录后能回到未登录前的页面（currentUrl）。
                            //当用户登录成功后，需要重新请求一次服务端，带上currentUrl。
                            //用该方法中的webview变量加载请求链接。
                            //服务端收到请求后在生成免登录url时，将currentUrl放入redirect参数，通知客户端302跳转到新生成的免登录URL。
                            new AlertDialog.Builder(webView.getContext())
                                    .setTitle("跳转登录")
                                    .setMessage("跳转到登录页面？")
                                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            mPopWindow.dismiss();
                                            ThirdPartyLoginActivity.startActivity(getContext());
                                        }
                                    })
                                    .setNegativeButton("否", null)
                                    .show();
                        }

                        /**
                         * 当点击“复制”按钮时，触发该方法，回调获取到券码code
                         * @param webView webview对象。
                         * @param code 复制的券码
                         */
                        public void onCopyCode(WebView webView, String code) {
                            //当未登录的用户点击去登录时，会调用此处代码。
                            new AlertDialog.Builder(webView.getContext())
                                    .setTitle("复制券码")
                                    .setMessage("已复制，券码为：" + code)
                                    .setPositiveButton("是", null)
                                    .setNegativeButton("否", null)
                                    .show();
                        }

                        /**
                         * 积分商城返回首页刷新积分时，触发该方法。
                         */
                        public void onLocalRefresh(WebView mWebView, String credits) {
                            //String credits为积分商城返回的最新积分，不保证准确。
                            //触发更新本地积分，这里建议用ajax向自己服务器请求积分值，比较准确。
                            Toast.makeText(getContext(), "触发本地刷新积分：" + credits, Toast.LENGTH_SHORT).show();
                        }
                    };
                } else {
                    mPopWindow.dismiss();
                    ThirdPartyLoginActivity.startActivity(getContext());
                }

            }
        });
    }

    @Override
    public void showLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoadingView() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (loadingLayout != null) {
                    loadingLayout.setVisibility(View.GONE);
                }
            }
        });

    }

    @Override
    public void showErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void LoadData(List<PictureBookMainPageBannerData> bannerlist, List<MainPageModuleData> modulelist) {
        this.bannerlist = bannerlist;
        updataBannerView();

        adapter.clearAll();
        adapter.appendToList(modulelist);
    }

    /**
     * 绘本步骤框
     *
     * @param url
     */
    private void showStepDailog(String url) {
        if (drawBookStepDailog == null) {
            drawBookStepDailog = new DrawBookStepDailog(getContext(), this, url);
            drawBookStepDailog.show();
//        } else if (!drawBookStepDailog.isShowing()) {
//            drawBookStepDailog.show();
        }
    }

    /**
     * 取消弹框
     */
    private void cancelStepDailog() {
        if (drawBookStepDailog != null) {
            drawBookStepDailog.dismiss();
            drawBookStepDailog = null;
        }
    }

    @Override
    public void setRefreshing(boolean isRefresh) {
        mainPageMPullRefreshView.setRefreshing(isRefresh);
    }

    @Override
    public void onResume() {
        super.onResume();
        startTimer();
        LogUtil.d("MainPageFragment", "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        cancelTimer();
        LogUtil.d("MainPageFragment", "onPause");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtil.d("MainPageFragment", "onHiddenChanged hidden: " + hidden);
        if (hidden) {
            cancelTimer();
        } else {
            startTimer();
        }
    }

    private void startTimer() {
        if (time != null) {
            time.start();
        }
    }

    private void cancelTimer() {
        if (time != null) {
            time.cancel();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.detachView();
        cancelTimer();
        time = null;
        cancelStepDailog();
    }
}